import org.omg.PortableInterceptor.INACTIVE;

import java.util.*;

/**
 * @Author 12629
 * @Date 2022/3/19 15:31
 * @Description：
 */

public class TestBinaryTree {

    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;
        /**
         * 构造方法，构造一个节点
         * @param val
         */
        public TreeNode(char val) {
            this.val = val;
        }
    }

    public TreeNode creteTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        //E.right = H;
        C.left = F;
        C.right = G;
        return A;//根节点
    }
    public TreeNode creteTree2() {
        TreeNode A = new TreeNode('1');
        TreeNode B = new TreeNode('2');
        TreeNode C = new TreeNode('3');

        A.right = B;
        B.left = C;
        return A;//根节点
    }



    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
    /**
     * 前序遍历
     * 遍历思路+子问题思路
     * @param root
     * @return
     */

   /* 子问题思路
   public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        list.add(root.val);

        List<Integer> leftList = preorderTraversal(root.left);
        list.addAll(leftList);

        List<Integer> rightList = preorderTraversal(root.right);
        list.addAll(rightList);

        return list;
    }*/

   /* 遍历思路
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        preorderTraversalChild(root,list);
        return list;
    }


    private List<Integer> preorderTraversalChild(TreeNode root,List<Integer> list) {
        if(root == null) {
            return null;
        }
        list.add(root.val);
        preorderTraversalChild(root.left,list);
        preorderTraversalChild(root.right,list);
        return list;
    }*/




    // 中序遍历
    void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }

    public static int count = 0;
    // 获取树中节点的个数         遍历思路：
    public void size1(TreeNode root){
        if(root == null) {
            return ;
        }
        count++;
        size1(root.right);
        size1(root.left);
    }

    /**
     * 子问题的思路
     * @param root
     * @return
     */
    public int size2(TreeNode root){
        if(root == null) {
            return 0;
        }
        //root不为空
        int tmp = size2(root.left) + size2(root.right)+1;
        return tmp;
    }


    public static int leafCount = 0;
    // 获取叶子节点的个数  遍历思路
    void getLeafNodeCount1(TreeNode root){
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            leafCount++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    // 获取叶子节点的个数  子问题
    int getLeafNodeCount2(TreeNode root){
        if(root == null) {
            return 0;
        }
        if(root.left == null && root.right == null) {
            return 1;
        }
        int tmp = getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
        return tmp;
    }


    // 获取第K层节点的个数
    int getKLevelNodeCount(TreeNode root,int k){
        if(root == null) {
            return 0;
        }
        if(k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1)
                + getKLevelNodeCount(root.right,k-1);
    }

    // 获取二叉树的高度
    int getHeight(TreeNode root){
        if(root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        int leftR = getHeight(root.right);
        return leftH > leftR ? leftH+1 : leftR+1;
    }

    // 检测值为value的元素是否存在
    TreeNode find(TreeNode root, int val){
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode ret = find(root.left,val);
        if(ret != null) {
            return ret;
        }
        ret = find(root.right,val);
        if(ret != null) {
            return ret;
        }
        return null;
    }

    // 判断一棵树是不是完全二叉树
    boolean isCompleteTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.offer(root);
        }

        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.peek();
            if(cur != null) {
                return false;
            }else {
                queue.poll();
            }
        }
        return true;
    }

    public void leveOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if(root != null) {
            queue.offer(root);
        }
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }


    public List<List<TreeNode>> levelOrder(TreeNode root) {
        List<List<TreeNode>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<TreeNode> curRow = new ArrayList<>();
            int size = queue.size();//2
            while (size != 0) {
                TreeNode cur = queue.poll();
                curRow.add(cur);
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;//0
            }
            ret.add(curRow);
        }
        return ret;
    }

    /**
     * 判断两颗树 是否是相同 二叉树
     * 时间复杂度：O(min(M,N))
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p != null && q == null  || p == null && q!= null) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        //p != null && q!= null
        if(p.val != q.val) {
            return false;
        }
        //p != null && q!= null  && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

    /**
     * 判断是不是子树
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {

        if(root == null || subRoot == null) return false;

        if(isSameTree(root,subRoot)) return true;

        if(isSubtree(root.left,subRoot))  return true;

        if(isSubtree(root.right,subRoot))  return true;

        return false;
    }

    /**
     * O(N)
     * @param root
     * @return
     */
    public int maxDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = maxDepth(root.left);
        int leftR = maxDepth(root.right);
        return leftH > leftR ? leftH+1 : leftR+1;
    }
    /**
     * 判断一棵树 是不是高度平衡的二叉树
     * O(N*N)
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        int leftH = maxDepth(root.left);
        int rightH = maxDepth(root.right);

        return Math.abs(leftH-rightH) <= 1 &&
                isBalanced(root.left) && isBalanced(root.right);
    }


    /**
     * 实现O（N）的时间，计算一棵树是不是平衡的
     * @param root
     * @return
     */
    public boolean isBalanced2(TreeNode root) {
        return  maxDepth2(root) >= 0;
    }

    public int maxDepth2(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftH = maxDepth2(root.left);
        int leftR = maxDepth2(root.right);

        if(leftH >= 0 && leftR >= 0 && Math.abs(leftH-leftR) <= 1) {
            return Math.max(leftH,leftR) +1;
        }else {
            return -1;//负数 说明不平衡
        }
    }

    /**
     * 判断是否是对称的
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }

    /**
     * 这里面判断 左树和右树是否是对称的
     * @param leftTree
     * @param rightTree
     * @return
     */
    private boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        //1、判断一个位空  一个不为空的情况下
        if(leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        //2、两个都为空
        if(leftTree == null && rightTree == null) {
            return true;
        }
        //3、值是不是一样的
        if(leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }

        if(root == p || root == q) {
            return root;
        }

        TreeNode leftTree = lowestCommonAncestor(root.left,p,q);

        TreeNode rightTree = lowestCommonAncestor(root.right,p,q);

        if(leftTree != null && rightTree != null) {
            return root;
        }

        if(leftTree != null) {
            return leftTree;
        }

        if(rightTree != null) {
            return rightTree;
        }
        return null;
    }

    public String tree2str(TreeNode root) {

        StringBuilder sb = new StringBuilder();
        if(root == null) {
            return sb.toString();
        }

        tree2strChild(root,sb);

        return new String(sb);
    }

    public void tree2strChild(TreeNode t,StringBuilder sb) {
        if(t == null) {
            return;
        }
        sb.append(t.val);

        if(t.left != null) {
            sb.append("(");
            tree2strChild(t.left,sb);
            sb.append(")");
        }else{
            if(t.right == null) {
                return;
            }else{
                sb.append("()");
            }
        }

        if(t.right == null) {
            return;
        }else{
            sb.append("(");
            tree2strChild(t.right,sb);
            sb.append(")");
        }
    }

    /**
     * 非递归实现前序遍历
     * @param root
     * @return
     */
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        /**
         * cur != null
         * !stack.empty()
         */
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                System.out.print(cur.val + " ");
                //ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }


    /**
     * 非递归实现 中序遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            //
            TreeNode top = stack.pop();
            System.out.println(top.val);
            //ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }


    /**
     * 非递归实现后续遍历
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        TreeNode prev = null;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();

            if (top.right == null || top.right == prev) {
                System.out.print(top.val + " ");
                //ret.add(top.val);
                stack.pop();
                prev = top;
            } else {
                cur = top.right;
            }
        }
        return ret;
    }
}
